package client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class ClientConnection {
	
	static Socket connectionSocket;
	
	/**
	 * To create Socket object, for both Server and Client
	 * @param ipAddress
	 * @param port
	 */
	public static boolean openConnection(String ipAddress,int port){
		boolean ret = true;
		
		try {
			connectionSocket = new Socket(ipAddress, port);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			ret = false;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			ret = false;
		}
		
		return ret;
	}
	
	/**
	 * Read the received message for Server
	 * @param port
	 * @return received message or empty message
	 * @throws Exception
	 */
	public static String receive(){
      String message = "";
      
      if (connectionSocket == null)
    	  return message; //or null?
      
	  try
	  {
          BufferedReader receiveObject = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));		          
          message = receiveObject.readLine();
          //receiveObject.close();
      }
	  catch (IOException e) {
		  e.printStackTrace();
		  System.out.println("Connection error (Client crash?)");
	  }
	  
	  return message;
	}
	
	public static String receive(String ipAddress,int port){
		String message = "";
	      
		  //make new connection
		  if (!openConnection(ipAddress,port))
			  return message;
	      
	      if (connectionSocket == null)
	    	  return message;
	      
		  try
		  {
	          BufferedReader receiveObject = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));		          
	          message = receiveObject.readLine();
	          //receiveObject.close();
	      }
		  catch (IOException e) {
			  e.printStackTrace();
			  System.out.println("Connection error (Client crash?)");
		  }
		  
		  return message;
	}
	
	/**
	 * Send out a message
	 * @param message
	 */
	public static boolean send(String message){	
		
		 if (connectionSocket == null)
	    	  return false; //
		
		boolean ret = true;
		PrintWriter sendObject = null;
		try {
			sendObject = new PrintWriter(connectionSocket.getOutputStream(), true);
			sendObject.println(message);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			ret = false;
		}			
		
		return ret;
	}
	
	/**
	 * To close connection of Socket object
	 * @throws Exception
	 */
	public static void closeConnection()
	{
		try {
			connectionSocket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
